package javax.net.p2p.bio.handler;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.p2p.api.P2PCommand;
import javax.net.p2p.api.P2PWrapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
 * **************************************************
 * @description 
 * @author   karl
 * @version  1.0, 2018-11-3
 * @see HISTORY
 *      Date        Desc          Author      Operation
 *  	2018-11-3   创建文件       karl        create
 * @since 2017 Phyrose Science & Technology (Kunming) Co., Ltd.
 **************************************************/
public class ChatClientHandler implements Runnable {

    private static final Log log = LogFactory.getLog(ChatClientHandler.class);

    private Socket socket;
    private String loginName;
    private ObjectOutputStream oos;
    private boolean running = true;

    public ChatClientHandler(Socket socket) {
        try {
            oos = new ObjectOutputStream(socket.getOutputStream());
        } catch (IOException ex) {
            log.error(ex);
        }
        this.socket = socket;
    }


    @Override
    public void run() {
        try {
            while (running) {
                //try {
                //if (socket.getInputStream().available() > 0) {
                try (
                        InputStream is = socket.getInputStream();) {
                    int len = 0;
                    byte[] b = new byte[1024];
                    while ((len = is.read(b)) != -1) {
                        String str = new String(b, 0, len);
                        System.out.println(str);
                    }
                } catch (Exception ex) {
                    log.error(ex);
                    break;
                }
                //}

//            } catch (IOException ex) {
//                log.error(ex);
//            }
            }
            System.out.println("客户端线程关闭：" + socket);
            clean();
        } catch (Exception ex) {
            Logger.getLogger(ChatClientHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void clean() {
        if (oos != null) {
            try {
                oos.close();
            } catch (IOException ex) {
                Logger.getLogger(ChatClientHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (socket != null) {
            try {
                socket.close();
                socket = null;
            } catch (IOException ex) {
                log.error(ex);
            }
        }
    }
    public void processChat(String str) throws IOException {
        //System.out.println("客户端线程消息处理：" + str);
        String[] strs = str.split(":");
        P2PWrapper<String> msg = new P2PWrapper();
        if (strs.length == 2) {
            String command = strs[0].trim();
            if ("login".equalsIgnoreCase(command)) {
                msg.setCommand(P2PCommand.LOGIN);
                loginName = strs[1];
                msg.setData(loginName);
            } else {
                msg.setCommand(P2PCommand.CHAT_ONE);
                msg.setData(str);
            }
        } else if ("logout".equalsIgnoreCase(str)) {
            if (loginName != null) {
                msg.setCommand(P2PCommand.LOGOUT);
                msg.setData(loginName);
            } else {
                return;
            }
        } else {
            msg.setCommand(P2PCommand.CHAT_ALL);
            msg.setData(str);
        }
        oos.writeObject(msg);
        oos.flush();
    }

}
